rm(list = ls())

library(tidyverse)
library(fixest)
library(broom)

## Get federal election data
## Note: In BTW, right_total_party = AfD + CDU/CSU

bt <- readRDS('data/federal_elections_clean.RDS') %>%
  mutate(year = date.id) %>% 
  mutate(other_party = 100 - right_total_party - left_total_party)

## Declare main data set 
## Declare main outcomes

bt_use <- bt %>% filter(year %in% c(2013, 2017))
dvars <- c('right_total_party',
           'left_total_party',
           'turnout_party',
           'cdu_csu_party',
           'greens_party',
           'left_party',
           'fdp_party',
           'spd_party',
           'other_party',
           'afd_party')
n_dvars <- length(dvars)

## Get main results 

m1 <- fixest::feols(.[dvars] ~ post + treated + treated_post, 
                    cluster = 'AA.district.id', data = bt_use %>% 
                      filter(state == "Nordrhein-Westfalen"))
m2 <- fixest::feols(.[dvars] ~ post + treated + treated_post, 
                    cluster = 'AA.district.id', data = bt_use %>% 
                      filter(state == "Bayern"))
m3 <- fixest::feols(.[dvars] ~ post*state + treated*state + treated_post, 
                    cluster = 'AA.district.id', data = bt_use %>% 
                      filter(state %in% c("Nordrhein-Westfalen",
                                          "Bayern")))

## Tidy these

l1 <- lapply(1:n_dvars, function(i) tidy(m1[[i]], conf.int = T)) %>% 
  reduce(rbind) %>% 
  mutate(sample = 'State: NRW, Federal election') %>% 
  filter(term == "treated_post") %>% 
  mutate(dv = dvars)
l2 <- lapply(1:n_dvars, function(i) tidy(m2[[i]], conf.int = T)) %>% 
  reduce(rbind) %>% 
  mutate(sample = 'State: BY, Federal election')%>% 
  filter(term == "treated_post") %>% 
  mutate(dv = dvars)
l3 <- lapply(1:n_dvars, function(i) tidy(m3[[i]], conf.int = T)) %>% 
  reduce(rbind) %>% 
  mutate(sample = 'State: NRW & BY, Federal election')%>% 
  filter(term == "treated_post") %>% 
  mutate(dv = dvars)

## Combine

df_btw <- bind_rows(l1, l2, l3) %>% 
  mutate(dv = recode(dv, 
                     `right_total_party` = 'Total right vote',
                     `left_total_party` = 'Total left vote',
                     `turnout_party` = 'Turnout',
                     `cdu_csu_party` = 'CDU/CSU',
                     `greens_party` = 'Greens',
                     `left_party` = 'Left party',
                     `fdp_party` = 'FDP',
                     `spd_party` = 'SPD',
                     `other_party` = 'Other',
                     `afd_party` = 'AfD'))

## State elections - BY ##

by <- readRDS('data/bavaria_elections_clean.rds') %>%
  filter(year %in% c(2013, 2018)) %>%
  dplyr::select(-year) %>%
  mutate(turnout = turnout / 100) %>% 
  mutate(totright2_nofdp = CSU_2 + ifelse(post == 1, AFD_2, 0))

## ## 

outcomevars <- c("CSU_2", "SPD_2", "Greens_2", 
                 "FDP_2", "other_2", 
                 "totleft2",
                 "totright2_nofdp",
                 "turnout")
n_dvars <- length(outcomevars)

## Need to multiply all by 100

by <- by %>% 
  mutate_at(vars(one_of(outcomevars)),
            list(~.*100))

## Models

m4_by <- fixest::feols(.[outcomevars] ~ post + treated + treated_post, 
                       cluster = 'AA.district.id', data = by)

l4_by <- lapply(1:n_dvars, function(i) tidy(m4_by[[i]], conf.int = T)) %>% 
  reduce(rbind) %>% 
  mutate(sample = 'State: BY, State election') %>% 
  filter(term == "treated_post") %>% 
  mutate(dv = outcomevars) %>% 
  mutate(dv = recode(dv, 
                     `totleft2` = 'Total left vote',
                     `totright2_nofdp` = 'Total right vote',
                     `turnout` = 'Turnout',
                     `CSU_2` = 'CDU/CSU',
                     `SPD_2` = 'SPD',
                     `FDP_2` = 'FDP',
                     `other_2` = 'Other',
                     `Greens_2` = 'Greens'))

## NRW 

nrw <- readRDS("data/nrw_elections_clean.rds")

outcomevars <- c('cdu_csu', 'fdp', 'greens',
                 'left', 'other_party', 'spd',
                 'left_total',
                 'turnout', 'totright2_nofdp')
n_dvars <- length(outcomevars)

## Estimate

m5_nrw <- fixest::feols(.[outcomevars] ~ post + treated + treated_post, 
                        cluster = 'AA.district.id', data = nrw)

l5_nrw <- lapply(1:n_dvars, function(i) tidy(m5_nrw[[i]], conf.int = T)) %>% 
  reduce(rbind) %>% 
  mutate(sample = 'State: NRW, State election') %>% 
  filter(term == "treated_post") %>% 
  mutate(dv = outcomevars) %>% 
  mutate(dv = recode(dv, 
                     `left_total` = 'Total left vote',
                     `totright2_nofdp` = 'Total right vote',
                     `turnout` = 'Turnout',
                     `greens` = 'Greens',
                     `left` = 'Left party',
                     `fdp` = 'FDP',
                     `cdu_csu` = 'CDU/CSU',
                     `spd` = 'SPD',
                     `other_party` = 'Other'))

#### Figure 4: Effect of Refugee Labor Market Access on Voting Behavior ####

plot_df <- df_btw %>% 
  bind_rows(l4_by) %>% 
  bind_rows(l5_nrw) %>% 
  mutate(election = ifelse(str_detect(sample, 
                                      "Federal"),
                           "Federal election",
                           "State election"),
         geopgrahy = str_remove_all(sample,
                                    ", State election|, Federal election"))

## ##

pd <- position_dodge(0.5)

p1 <- ggplot(plot_df %>% 
               filter(str_detect(dv, "Total")), 
             aes(dv, estimate, geopgrahy)) +
  geom_hline(yintercept = 0, linetype = 'dotted') +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high,
                    color = geopgrahy),
                width = 0, position = pd) +
  geom_point(aes(shape = geopgrahy), fill = 'white',
             position = pd, size = 2) +
  ylab('Effect of Liberalization on Vote Share') + 
  xlab('') + 
  theme_bw() +
  scale_color_grey(name = '')+
  scale_shape_manual(values = c(21,22,23),
                     name= '') +
  facet_wrap(~election) +
  coord_flip() + 
  theme(legend.position = 'bottom',
        legend.key.size = unit(0.8, 'cm'))
p1

#### Figure A.8: Refugee Labor Market Access and Electoral Behavior, Disaggregated by Party ####

plot_df <- plot_df %>% 
  mutate(sample = factor(sample, levels = unique(sample)[c(2,4,1,5,3)]))

p1 <- ggplot(plot_df, aes(dv, estimate)) +
  geom_hline(yintercept = 0, linetype = 'dotted', color = 'grey40') +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0) +
  geom_point(fill = 'white', size = 2, shape = 21) +
  ylab('Effect of Liberalization on Vote Share') + 
  xlab('') + 
  theme_bw() +
  facet_wrap(~sample, 
             ncol = 2) +
  coord_flip() + 
  theme(legend.position = 'bottom')
p1

